package com.stox.ui.javafx.core.widget;

import javafx.event.EventHandler;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;

import com.stox.dto.AbstractModel;

public class EditableAbstractModelTreeCell extends AbstractModelTreeCell{

	private EventHandler<KeyEvent> editHandler;
	
	private TextField textField;

	public EditableAbstractModelTreeCell() {
		setEditable(true);
	}
	
	private void init(){
		if(null == textField) textField = new TextField();
		if(null == editHandler) editHandler = new EventHandler<KeyEvent>(){
			@Override
			public void handle(KeyEvent event) {
				if(KeyCode.ESCAPE.equals(event.getCode())){
					cancelEdit();
				}
				if(KeyCode.ENTER.equals(event.getCode())){
					commitEdit(getTreeItem().getValue());
				}
			}
		};
		textField.addEventHandler(KeyEvent.KEY_PRESSED, editHandler);
	}
	
	@Override
	public void startEdit() {
		super.startEdit();
		init();
		textField.setText(getText());
		setGraphic(textField);
		setText(null);
	}
	
	@Override
	public void cancelEdit() {
		setGraphic(null);
		if(null != getTreeItem() && null != getTreeItem().getValue()){
			setText(getTreeItem().getValue().getName());
		}
		super.cancelEdit();
	}
	
	@Override
	public void commitEdit(AbstractModel abstractModel) {
		setText(textField.getText());
		abstractModel.setName(textField.getText());
		setGraphic(null);
		super.commitEdit(abstractModel);
	}
	
}
